package com.wingsofts.gankclient.ui.widget

import android.content.Context
import android.support.v4.content.ContextCompat
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.widget.ProgressBar
import com.wingsofts.gankclient.R

/**
 * Created by wing on 16-11-25.
 */
class ProgressWebView
@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, style: Int = 0)
    : WebView(context, attrs, style) {

    private val progressbar: ProgressBar = ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal)
            .apply {
                layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1f, context.resources.displayMetrics).toInt()
                )

                progressDrawable = ContextCompat.getDrawable(context, R.drawable.progress_bar)
            }

    init {
        addView(progressbar)
        setWebChromeClient(object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                if (newProgress == 100) {
                    progressbar.visibility = View.GONE
                } else {
                    if (progressbar.visibility == View.GONE)
                        progressbar.visibility = View.VISIBLE
                    progressbar.progress = newProgress
                }
                super.onProgressChanged(view, newProgress)
            }
        })
        settings.builtInZoomControls = true
    }
}
